package com.boang.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.boang.entity.PO.Reservation;
import com.boang.entity.PO.Venue;
import com.boang.mapper.ReservationMapper;
import com.boang.mapper.VenueMapper;
import com.boang.service.ReservationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 22567
 * @description 针对表【reservation】的数据库操作Service实现
 * @createDate 2025-03-10 15:47:56
 */
@Service
public class ReservationServiceImpl extends ServiceImpl<ReservationMapper, Reservation>
        implements ReservationService {
    @Autowired
    private ReservationMapper reservationMapper;
    @Autowired
    private VenueMapper venueMapper;

    /**
     * 创建预约（核心逻辑）
     */
    public Reservation createReservation(Reservation reservation) {
        // 1. 检查场地是否存在且可用
        Venue venue = venueMapper.selectVenueById(reservation.getVenueId());
        if (venue == null || !"可预约".equals(venue.getStatus())) {
            throw new IllegalArgumentException("场地不可用");
        }

        // 2. 检查时间冲突
        List<Reservation> conflicts = reservationMapper.checkTimeConflict(
                reservation.getVenueId(),
                reservation.getStartTime(),
                reservation.getEndTime()
        );
        if (!conflicts.isEmpty()) {
            throw new IllegalArgumentException("时间段已被预约");
        }

        // 3. 设置默认状态并保存
        reservation.setStatus("已预约");
        reservationMapper.insertReservation(reservation);
        return reservation;
    }

    /**
     * 取消预约
     */
    public void cancelReservation(Long reservationId) {
        int updated = reservationMapper.cancelReservation(reservationId);
        if (updated == 0) {
            throw new IllegalArgumentException("预约不存在或已取消");
        }
    }

    public List<Reservation> getAllReservations() {
        return reservationMapper.selectAllReservations();
    }

    public List<Reservation> getReservationsByUserId(String userId) {
        return reservationMapper.selectReservationsByUserId(userId);
    }

    public List<Reservation> getReservationsByVenueId(Long venueId) {
        return reservationMapper.selectReservationsByVenueId(venueId);
    }

}




